package com.rizzo.shell.plugins;

import com.rizzo.shell.intern.args.MysqlTransferArguments;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.logging.Logger;

@Configuration
public class MysqlConfig {

    public static final String MYSQL_URL_PREFIX = "jdbc:mysql://";
    public static final String H2_URL_PREFIX = "jdbc:h2:tcp://";
    public static final String H2_URL_SUFFIX = ";DB_CLOSE_DELAY=-1;MODE=MySQL";
    private static Logger logger = Logger.getLogger("com.rizzo.shell.plugins.MysqlConfig");

    @Resource(name = "mysqlArgs")
    private HashMap<MysqlTransferArguments, String> args;

    @Bean
    public DriverManagerDataSource mysqlDataSource() {
        if (Boolean.parseBoolean(args.get(MysqlTransferArguments.DEV))) {
            String url = H2_URL_PREFIX + args.get(MysqlTransferArguments.HOST) + ":"
                    + args.get(MysqlTransferArguments.PORT) + "/mem:" + args.get(MysqlTransferArguments.DATABASE) + H2_URL_SUFFIX;
            DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(url,
                    args.get(MysqlTransferArguments.USERNAME), args.get(MysqlTransferArguments.PASSWORD));
            driverManagerDataSource.setDriverClassName("org.h2.Driver");
            return driverManagerDataSource;
        } else {
            String url = MYSQL_URL_PREFIX + args.get(MysqlTransferArguments.HOST) + ":"
                    + args.get(MysqlTransferArguments.PORT) + "/" + args.get(MysqlTransferArguments.DATABASE);
            DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(url,
                    args.get(MysqlTransferArguments.USERNAME), args.get(MysqlTransferArguments.PASSWORD));
            driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
            return driverManagerDataSource;
        }

    }

    @Bean(name = "jdbcTemplate")
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(mysqlDataSource());
    }

}
